<?php

/*
 * Defines the data interface that is passed on to the javascript on the browser 
 * using json
 * Gives the template for creating the relevant html and javascript code.
 */
abstract class Data
{
    //defines the data that is passed along
    private $data = null;
    private $module_list = array();
    private $module_title = array();


    private function getModuleList() {
        //$dn = ".";
        $dn = "/var/webi/html/config";
        $filearray = scandir($dn);
        if ( $filearray == false ) {
            return false;
        }
        foreach ( $filearray as $arrval ) {
            if ( preg_match("/.*.php/", $arrval) && 
                !preg_match("/interface.php/", $arrval) &&
                !preg_match("/index.php/", $arrval)) {

                //array_push($this->module_list, trim($arrval, ".php"));
                $key = trim($arrval, ".php");

                $filedata = file($dn.'/'.$arrval);
                if ( $filedata == false ) {
                    echo "file not found";
                    return false;
                }

                foreach ( $filedata as $f ) {
                    if ( strstr($f, "title") ) {
                        list($val1, $val2) = split('"', $f);
                        $this->module_list[$key] = trim($val2);
                    }
                }
            }
        }
    }

    function getJSON() {
        $obj = $this->readDataFromSystem();

        if($obj) {
            $jsonstr = json_encode($obj);
        }
        return $jsonstr;
    }

    function setJSON($jsonstr) {
        $obj = json_decode($jsonstr, true);
        return $this->commitDataToSystem($obj);
    }

    function addData($key, $data) {
        $this->data[$key] = $data;
    }

    function printData() {
        var_dump($this->data);
    }

    function pushToArray($obj) {
        array_push($this->data, $obj);
    }

    //application specific override these
    //read the data from files on the system and collect them
    //into a json object
    abstract function readDataFromSystem();

    //write the data to the files on the system and run necessary
    //scripts if needed.
    abstract function commitDataToSystem($obj);

/**************************
print the head element for the page.
/**************************/
    function printHeader() {
        $str = <<<END

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>LAB - $this->title </title>
<link type="text/css" href="../css/theme/jquery-ui.css" rel="stylesheet" />
<link type="text/css" href="../css/main.css" rel="stylesheet" />
<script type="text/javascript" src="../js/jquery.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui.min.js"></script>
<script type="text/javascript" src="../js/json2.js"></script>

END;
        return $str;
    }


/**************************
print the body
/**************************/
    function printBody() {

        $this->getModuleList();

        $str = <<<END

        <div id="header" class="ui-widget-header">
            <h1>Linux Appliance Box</h1>
            <a href="http://www.linuxappliancebox.com" target="_blank">www.linuxappliancebox.com</a>
        </div>

        <div id="lp_id" class="leftPane">
            <h3 id="home" class="section"><a href="/index.html">Dashboard</a></h3>
            <h3 id="home" class="section"><a href="/shell.html">Shell Access</a></h3>
            <h3 class="section">Configuration</h3>
            <ul class="content">
END;

        foreach($this->module_list as $k => $m) {
            if($k == $this->module) {
                $str .= "\t\t<li><a href='/config/index.php?m=html&module=$k' style='background-color:#eeeeee;'>$this->title</a></li>\n";
            }
            else {
                $str .= "\t\t<li><a href='/config/index.php?m=html&module=$k'>$m</a></li>\n";
            }
        }

        $str .= <<<END
            </ul>
            <h3 class="section">Monitoring</h3>
            <ul class="content">
                <li><a href="/monitor/index.html">System</a></li>
            </ul>
        </div>
END;

        return $str;
    }

/*************************
header script to add the JSON interface between the server-side php script 
 and client-side javascript.
/*************************/
    function printHeaderScript() {
        $str = <<<END

<script type="text/javascript">

    $(function() {
        init();
    });

    //step
    // Data = recvData() -> writeDataToHTML(Data) -> submit -> Data = readDataFromHTML() -> sendData(Data)

    function init() {
        recvData();
        $('#submit').click(function(){ 
            var d = readDataFromHTML();
            var msg = validate(d);
            if (msg) {
                alert(msg);
                return null;
            }
            if(d) {
                sendData(d, true);
                return 0;
            }
        });
    }

    //recv the data from the server
    function recvData() {
        var data;
        $.ajax({
            type: "GET",
            url: "/config/index.php?m=get&module=$this->module",
            dataType: "json",
            success: writeDataToHTML
        });
    }

    //send the data to the server and report status
    function sendData(ra, async) {
        var jsonstr = JSON.stringify(ra);
        var msg;
        $.ajax({
            type: "POST",
            url: "/config/index.php?m=set&module=$this->module",
            data: jsonstr,
            dataType: "text",
            async: async,
            beforeSend: beforeSendFunction,
            success: successFunction,
            error: errorFunction
        });
    }
</script>

END;
        return $str;
    }


/*********************
 print the template script. 
 Real script is in the specific module or separate html file.
 *********************/
    function printModuleScript() {
        $str = <<<END

<script type="text/javascript">
    function validate(obj) {
        //add any validation code here. It must return a text 
        //string with error or null in case of success
        var msg = null;
        return msg;
    }

    //fill in the obj to be sent to the server using the form values
    function readDataFromHTML() {
        var data = Object();
        return data;
    }

    //fill in the form using values received from server
    function writeDataToHTML(data) {
    }

</script>

END;
        return $str;
    }

/*********************
 print the template html. 
 Real html is in the specific <module>.php or separate html file.
 *********************/
    function printModuleHTML() {
        $str = <<<END
<h3> This is a template. Please fill in your html code in the module specific php file </h3>

END;
        return $str;
    }
}

class ModuleFactory {

    public static function createModule($module) {
        $class = ucfirst($module);
        $file = $module.'.php'; 

        include_once($file);

        if(class_exists($class) && is_subclass_of($class, "Data"))
            return new $class;
        else
            throw new Exception("Cannot find '$module' module.");
    }
}

?>
